package model

import (
	"database/sql/driver"
	"errors"
	"github.com/bwmarrin/snowflake"
	"strconv"
)

type SnowflakeIdType snowflake.ID

// MarshalJSON returns a json byte array string of the snowflake ID.
func (s SnowflakeIdType) MarshalJSON() ([]byte, error) {
	d := snowflake.ID(s)
	return d.MarshalJSON()
}

// UnmarshalJSON converts a json byte array of a snowflake ID into an ID type.
func (s *SnowflakeIdType) UnmarshalJSON(b []byte) error {
	if len(b) < 3 || b[0] != '"' || b[len(b)-1] != '"' {
		return snowflake.JSONSyntaxError{}
	}

	i, err := strconv.ParseInt(string(b[1:len(b)-1]), 10, 64)
	if err != nil {
		return err
	}

	*s = SnowflakeIdType(i)
	return nil
}
func (s SnowflakeIdType) Value() (driver.Value, error) {
	return int64(s), nil
}
func (s *SnowflakeIdType) Scan(v any) error {
	if value, ok := v.(int64); ok {
		*s = SnowflakeIdType(value)
		return nil
	}
	return errors.New("not int64")
}
